import Vue from 'vue'
import VueRouter from "vue-router";
Vue.use(VueRouter)

const router = new VueRouter({
  // /article 路径 → Article组件
  routes: [
    { 
      path: '/',
      component: () => import('@/views/blog/Layout.vue'),
      redirect: '/article',
      // 通过 children 配置项，可以配置嵌套子路由
      // 1. 在children配置项中，配规则
      // 2. 准备二级路由出口
      children: [
        {
          path: '/article',
          component: () => import('@/views/blog/Article.vue')
        },
        {
          path: '/writeBlog',
          component: () => import('@/views/blog/WriteBlog.vue')
        },
        {
          path: '/like',
          component: () => import('@/views/blog/Like.vue')
        },
        {
          path: '/user',
          component: () => import('@/views/blog/User.vue')
        },
        {
          path: '/test',
          component: () => import('@/views/blog/test.vue')
        },
      ]
    },
    {
      path: '/detail/:id',
      component: () => import('@/views/blog/ArticleDetail.vue')
    },
    {
      path: '/login',
      component: () => import('@/views/login/index.vue')
    },
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const publicPages = ['/login']; // 公开页面列表
  const authRequired = !publicPages.includes(to.path);

  if (authRequired && !token) {
    // 如果访问受保护页面且没有 token，则重定向到登录页面
    alert('请先登录');
    next('/login');
  } else {
    // 否则继续导航
    next();
  }
});

export default router